package org.csu.new_jpetstore_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.new_jpetstore_backend.common.CommonResponse;
import org.csu.new_jpetstore_backend.entity.Item;
import org.csu.new_jpetstore_backend.entity.Product;
import org.csu.new_jpetstore_backend.persistence.ItemMapper;
import org.csu.new_jpetstore_backend.persistence.ProductMapper;
import org.csu.new_jpetstore_backend.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("ProductService")
public class ProductServiceImpl implements ProductService {

    @Autowired
    ItemMapper itemMapper;
    @Autowired
    ProductMapper productMapper;

    @Override
    public CommonResponse<Object> getItemByProductId(String productId) {
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("productid", productId);
        List<Item> itemList = itemMapper.selectList(queryWrapper);
        if(itemList.isEmpty()){
            return CommonResponse.createForSuccessMessage("have not such Item!");
        }
        return CommonResponse.createForSuccess("getItems Success!", itemList);
    }

    @Override
    public CommonResponse<Object> SearchByProductName(String name) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        Product product = productMapper.selectOne(queryWrapper);
        if(product == null){
            return CommonResponse.createForSuccessMessage("have no such product!");
        }
        return CommonResponse.createForSuccess("search success!", product);
    }

    @Override
    public CommonResponse<Object> GetAllProducts() {
        List<Product> productList = productMapper.selectList(null);
        if(productList == null){
            return CommonResponse.createForSuccessMessage("have not products!");
        }
        return CommonResponse.createForSuccess("get success!", productList);
    }

    @Override
    public CommonResponse<List<Product>> searchProducts(String keyword){
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("productid", keyword).or()
                .like("category", keyword).or()
                .like("name", keyword);
        List<Product> productList = productMapper.selectList(queryWrapper);

        if (productList.isEmpty()){
            return CommonResponse.createForSuccessMessage("未搜索到相关产品");
        }

        return CommonResponse.createForSuccess(productList);
    }
}
